/*
 *    This file is part of SSHTunneler.
 *
 *    Copyright 2009 Jean-Sebastien Gelinas <calestar@gmail.com>
 *
 *    SSHTunneler is free software: you can redistribute it and/or modify
 *    it under the terms of the GNU General Public License as published by
 *    the Free Software Foundation, either version 3 of the License, or
 *    (at your option) any later version.
 *
 *    SSHTunneler is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    GNU General Public License for more details.
 *
 *    You should have received a copy of the GNU General Public License
 *    along with SSHTunneler.  If not, see <http://www.gnu.org/licenses/>.
 *
 */
package sshtunneler.client.tray;

import java.awt.AWTException;
import java.awt.Image;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionListener;
import java.awt.event.MouseListener;

public class SysTrayManager {

	public static SysTrayManager inst = new SysTrayManager();
	public boolean can_use_systray = false;

	private int major_version = 0;
	private int minor_version = 0;
	@SuppressWarnings("unused")
	private String revision = "";

	private TrayIcon trayIcon = null;

	private SysTrayManager() {
		String str_version = System.getProperty("java.version");
		if (str_version == null || str_version.equals("")) {
			return;
		}

		// str_version should look like : "1.6.0_02"
		int first_dot_index = str_version.indexOf('.');
		int last_dot_index = str_version.lastIndexOf('.');

		this.major_version = Integer.parseInt(str_version.substring(0,
				first_dot_index));
		this.minor_version = Integer.parseInt(str_version.substring(
				first_dot_index + 1, last_dot_index));
		this.revision = str_version.substring(last_dot_index + 1);

		this.check_if_can_use_systray();
	}

	private void check_if_can_use_systray() {
		if (this.major_version >= 1 && this.minor_version >= 6) {
			this.can_use_systray = SystemTray.isSupported();
		}
	}

	public TrayIcon getTrayIcon() {
		return this.trayIcon;
	}

	public boolean install_icon(MouseListener mouseListener,
			ActionListener actionListener, PopupMenu menu, String title,
			Image image) throws AWTException {
		if (!this.can_use_systray || this.trayIcon != null) {
			return false;
		}
		this.trayIcon = new TrayIcon(image, title, menu);
		this.trayIcon.setImageAutoSize(true);
		this.trayIcon.addActionListener(actionListener);
		this.trayIcon.addMouseListener(mouseListener);

		SystemTray.getSystemTray().add(this.trayIcon);
		return true;
	}

	public boolean installed() {
		return this.trayIcon != null;
	}
}
